package com.sbtr.controller.classify;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sbtr.business.classify.dto.AlgoTemplateConditionDto;
import com.sbtr.business.classify.entity.AlgoClipRecord;
import com.sbtr.business.classify.entity.AlgoCondition;
import com.sbtr.business.classify.entity.AlgoTemplateCondition;
import com.sbtr.business.classify.entity.AlgoVersionFile;
import com.sbtr.business.classify.service.*;
import com.sbtr.business.classify.vo.AlgoConditionListVO;
import com.sbtr.business.classify.vo.AlgoConditionSaveVO;
import com.sbtr.business.classify.vo.AlgoTemplateConditionVO;
import com.sbtr.common.PageDto;
import com.sbtr.common.Response;
import com.sbtr.common.file.FileService;
import com.sbtr.controller.common.CommonController;
import com.sbtr.exception.BDException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 裁剪条件关联 前端控制器
 *
 * @author dgl
 * @since 2023-09-01
 */
@RestController
@RequestMapping("/algoTemplateCondition")
@Api(tags = "裁剪条件关联")
public class AlgoTemplateConditionController extends CommonController<AlgoTemplateCondition, AlgoTemplateConditionService> {

    @Autowired
    AlgoConditionService algoConditionService;

    @Autowired
    AlgoCorpgenerateService algoCorpgenerateService;

    @Autowired
    AlgoVersionFileService algoVersionFileService;
    @Autowired
    AlgoTemplateFileService algoTemplateFileService;


    @Autowired
    FileService fileService;


    @GetMapping("/pageList")
    @ApiOperation(httpMethod = "GET", value = "分页列表")
    public Response<PageDto<AlgoTemplateCondition>> pageList(AlgoTemplateConditionDto algoTemplateConditionDto) {
        return Response.success(u.pageList(algoTemplateConditionDto));
    }

    @PostMapping("/save")
    @ApiOperation(httpMethod = "POST", value = "保存")
    public Response<AlgoTemplateCondition> save(@RequestBody AlgoTemplateCondition algoTemplateCondition) {
        algoTemplateCondition.setId(null);
        if (algoTemplateCondition.insert()) {
            return Response.success(algoTemplateCondition);
        } else throw new BDException("保存失败");
    }

    @GetMapping("/getConditionByParams")
    @ApiOperation(httpMethod = "GET", value = "根据算法模板参数获取已设置条件列表，客户，管理员")
    public Response<List<AlgoConditionListVO>> getConditionByParams(AlgoTemplateCondition algoTemplateCondition) {

        QueryWrapper<AlgoTemplateCondition> queryWrapper = new QueryWrapper<>(algoTemplateCondition);
        List<AlgoTemplateCondition> list = u.list(queryWrapper);

        if (CollectionUtil.isEmpty(list)) {
            return Response.success(new ArrayList<>());
        }
        List<Long> versionIds = new ArrayList<>();

        for (AlgoTemplateCondition algoTemplateCondition2 : list) {
            versionIds.add(algoTemplateCondition2.getAlgoConditionId());
        }

        QueryWrapper<AlgoCondition> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("id", versionIds);
        List<AlgoCondition> list1 = algoConditionService.list(queryWrapper1);

        List<AlgoConditionListVO> data = new ArrayList<>();
        Map<String, List<Map<String, String>>> params = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list1)) {
            for (AlgoCondition algoCondition : list1) {
                if (CollectionUtils.isEmpty(params.get(algoCondition.getName()))) {
                    List<Map<String, String>> param = new ArrayList<>();
                    Map<String, String> map = new HashMap<>();
                    map.put("id", String.valueOf(algoCondition.getId()));
                    map.put("parameters", algoCondition.getParameters());
                    param.add(map);
                    params.put(algoCondition.getName(), param);
                } else {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", String.valueOf(algoCondition.getId()));
                    map.put("parameters", algoCondition.getParameters());
                    params.get(algoCondition.getName()).add(map);
                }
            }
        }

        for (Map.Entry<String, List<Map<String, String>>> mapParam : params.entrySet()) {
            AlgoConditionListVO algoConditionListVO = new AlgoConditionListVO();
            algoConditionListVO.setName(mapParam.getKey());
            algoConditionListVO.setParametersList(mapParam.getValue());
            data.add(algoConditionListVO);
        }

        return Response.success(data);
    }

    @PostMapping("/batchOptBfClearCondition")
    @ApiOperation(httpMethod = "POST", value = "批量修改条件和关联，库存，管理员")
    public Response<String> batchOptBfClearCondition(@RequestBody List<AlgoConditionSaveVO> t, Long algoTemplateVersionId, Long algoTemplateId) {
        u.batchOptBfClearCondition(t, algoTemplateVersionId, algoTemplateId);
        return Response.success("修改成功");
    }


    @PostMapping("/selectAlgoTemplateVersion")
    @ApiOperation(httpMethod = "POST", value = "根据条件和权重选择算法模板版本,轻量化，客户")
    public void selectAlgoTemplateVersion(@RequestBody List<AlgoTemplateConditionVO> list, Long algoTemplateId, HttpServletResponse resp) throws UnsupportedEncodingException {
        list.sort(Comparator.comparingDouble(AlgoTemplateConditionVO::getRate));

        List<Long> algoConditionIds = list.stream().map(AlgoTemplateConditionVO::getAlgoConditionId).collect(Collectors.toList());

        QueryWrapper<AlgoTemplateCondition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("algo_template_id", algoTemplateId);
        queryWrapper.in("algo_condition_id", algoConditionIds);
        List<AlgoTemplateCondition> curList = u.list(queryWrapper);

        for (int i = list.size() - 1; i > 0; i--) {
            AlgoTemplateConditionVO algoTemplateConditionVO = list.get(i);
            List<AlgoTemplateCondition> temList = new ArrayList<>();
            for (AlgoTemplateCondition algoTemplateCondition : curList) {
                if (algoTemplateCondition.getAlgoConditionId().equals(algoTemplateConditionVO.getAlgoConditionId())) {
                    temList.add(algoTemplateCondition);
                }
            }
            if (temList.size() == 0) {
                break;
            }
            curList = temList;
        }
        if (curList.size() == 0) {
            throw new BDException("服务器错误");
        }

        AlgoTemplateCondition algoTemplateCondition = curList.get(0);

//        AlgoTemplateFile algoTemplateFile = algoTemplateFileService.getById(algoTemplateId);


//        AlgoVersionFile algoVersionFile = algoVersionFileService.getById(algoTemplateCondition.getAlgoTemplateVersionId());

        AlgoVersionFile algoVersionFile = algoVersionFileService.download(algoTemplateCondition.getAlgoTemplateVersionId().toString());
        fileService.downloadFile(resp, algoVersionFile.getFileUrl(), URLEncoder.encode(algoVersionFile.getFileName(), "utf-8"));

        QueryWrapper<AlgoCondition> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("id", algoConditionIds);
        List<AlgoCondition> algoConditions = algoConditionService.list(queryWrapper2);

        JSONArray array = new JSONArray();
        if (CollectionUtil.size(algoConditions) != 0) {
            for (AlgoCondition algoCondition : algoConditions) {
                JSONObject condition = new JSONObject();
                condition.put("name", algoCondition.getName());
                condition.put("parameters", algoCondition.getParameters());
                for (AlgoTemplateConditionVO algoTemplateConditionVO : list) {
                    if (Objects.equals(algoTemplateConditionVO.getAlgoConditionId(), algoCondition.getId())) {
                        condition.put("rate", algoTemplateConditionVO.getRate());
                    }
                }
                array.add(condition);
            }
        }

        AlgoClipRecord algoClipRecord = new AlgoClipRecord();
        algoClipRecord.setFileName(algoVersionFile.getFileName());
        algoClipRecord.setConditionJson(JSONUtil.toJsonStr(array));
        algoClipRecord.setTemplateId(algoTemplateId);
        algoClipRecord.setClipFile(algoVersionFile.getFileUrl());
        algoClipRecord.insert();

//        String modelName = algoTemplateFile.getAlgoname() + "-" + new Date().getTime() + ".zip";
//
//        String path1 = this.getClass().getResource("/generate/addition/pearsonr.zip").getPath();
//
//
//        File zipFile = new File(modelName);
//        List<File> fileList = new ArrayList<>();
////        fileList.add(new File(path1));
//        fileList.add(new File(algoVersionFile.getFileUrl()));
//
//        //压缩多文件
//        ZipUtil.zip(zipFile, false, fileList.toArray(new File[0]));
//
//        FileHelper.zipFileList(modelName, fileList, resp);

    }

    @PostMapping("/downloadAlgoTemplateVersion")
    @ApiOperation(httpMethod = "POST", value = "下载算法版本文件第一个")
    public void downloadAlgoTemplateVersion(Long algoTemplateId, HttpServletResponse resp) throws UnsupportedEncodingException {
        QueryWrapper<AlgoTemplateCondition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("algo_template_id", algoTemplateId);
        List<AlgoTemplateCondition> curList = u.list(queryWrapper);

        AlgoTemplateCondition algoTemplateCondition = curList.get(0);

        AlgoVersionFile algoVersionFile = algoVersionFileService.download(algoTemplateCondition.getAlgoTemplateVersionId().toString());
        fileService.downloadFile(resp, algoVersionFile.getFileUrl(), URLEncoder.encode(algoVersionFile.getFileName(), "utf-8"));

    }
//    @Autowired
//    DictionaryService dictionaryService;
//    @Autowired
//    DictionaryParamService dictionaryParamService;
//
//
//    public List<DictionaryTreeDto> TreeList(String dirCodes, Dictionary dictionary) {
//        QueryWrapper<Dictionary> dictionaryWrapper = new QueryWrapper<>(dictionary);
//        if(StringUtils.isNotBlank(dirCodes)){
//            dictionaryWrapper.like("dir_code",dirCodes);
//        }
//        dictionaryWrapper.orderByAsc("number");
//        List<Dictionary> list = dictionaryService.list(dictionaryWrapper);
//        List<Long> ids = new ArrayList<>();
//
//        for (Dictionary dictionary1 : list) {
//            ids.add(dictionary1.getId());
//        }
//
//        QueryWrapper<DictionaryParam> dictionaryParamWrapper = new QueryWrapper<>();
//        dictionaryParamWrapper.in("dir_id", ids);
//        dictionaryParamWrapper.orderByAsc("number");
//
//        //迭代二级制作嵌套菜单结构
//        List<DictionaryParam> dictionaryParamList = dictionaryParamService.list(dictionaryParamWrapper);
//        List<DictionaryTreeDto> treeDtos = new ArrayList<>();
//        for (Dictionary dictionary1 : list) {//迭代设置字典选项内容
//            DictionaryTreeDto dictionaryTreeDto = BeanCopyUtils.copyProperties(dictionary1, DictionaryTreeDto.class);
//            dictionaryTreeDto.setChildrenParams(new ArrayList<>());
//            for (DictionaryParam dictionaryParam : dictionaryParamList) {
//                if (dictionaryParam.getDirId().equals(dictionary1.getId())) {
//                    dictionaryTreeDto.getChildrenParams().add(dictionaryParam);
//                }
//            }
//            treeDtos.add(dictionaryTreeDto);
//        }
//
//        return treeDtos;
//    }
//    @PostConstruct
//    public void init(){
//
//        List<DictionaryTreeDto> treeDtos=TreeList("model_",new Dictionary());
//
//        List<AlgoCondition> list = new ArrayList<>();
//        for (DictionaryTreeDto dictionaryTreeDto:treeDtos) {
//            for (DictionaryParam dictionaryParam:dictionaryTreeDto.getChildrenParams()) {
//                AlgoCondition algoCondition = new AlgoCondition();
//                algoCondition.setName(dictionaryTreeDto.getDirName());
//                algoCondition.setParameters(dictionaryParam.getOptName());
//                algoCondition.setType(2);
//                list.add(algoCondition);
//            }
//        }
//        algoConditionService.saveBatch(list);
//    }


}

